home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / gnu / libg_261.zip / libg_261 / libg++ / src / gen / Vec.ccP < prev    next >
Text File  |  1994-06-28  |  12KB  |  471 lines

  1. // This may look like C code, but it is really -*- C++ -*-
  2. /* 
  3. Copyright (C) 1988 Free Software Foundation
  4.     written by Doug Lea (dl@rocky.oswego.edu)
  5.  
  6. This file is part of the GNU C++ Library.  This library is free
  7. software; you can redistribute it and/or modify it under the terms of
  8. the GNU Library General Public License as published by the Free
  9. Software Foundation; either version 2 of the License, or (at your
  10. option) any later version.  This library is distributed in the hope
  11. that it will be useful, but WITHOUT ANY WARRANTY; without even the
  12. implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  13. PURPOSE.  See the GNU Library General Public License for more details.
  14. You should have received a copy of the GNU Library General Public
  15. License along with this library; if not, write to the Free Software
  16. Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  17. */
  18.  
  19. #ifdef __GNUG__
  20. #pragma implementation
  21. #endif
  22. #include <stream.h>
  23. #include <builtin.h>
  24. #include "<T>.Vec.h"
  25.  
  26. // error handling
  27.  
  28.  
  29. void default_<T>Vec_error_handler(const char* msg)
  30. {
  31.   cerr << "Fatal <T>Vec error. " << msg << "\n";
  32.   exit(1);
  33. }
  34.  
  35. one_arg_error_handler_t <T>Vec_error_handler = default_<T>Vec_error_handler;
  36.  
  37. one_arg_error_handler_t set_<T>Vec_error_handler(one_arg_error_handler_t f)
  38. {
  39.   one_arg_error_handler_t old = <T>Vec_error_handler;
  40.   <T>Vec_error_handler = f;
  41.   return old;
  42. }
  43.  
  44. void <T>Vec::error(const char* msg)
  45. {
  46.   (*<T>Vec_error_handler)(msg);
  47. }
  48.  
  49. void <T>Vec::range_error()
  50. {
  51.   (*<T>Vec_error_handler)("Index out of range.");
  52. }
  53.  
  54. <T>Vec::<T>Vec(const <T>Vec& v)
  55. {
  56.   s = new <T> [len = v.len];
  57.   <T>* top = &(s[len]);
  58.   <T>* t = s;
  59.   const <T>* u = v.s;
  60.   while (t < top) *t++ = *u++;
  61. }
  62.  
  63. <T>Vec::<T>Vec(int l, <T&> fill_value)
  64. {
  65.   s = new <T> [len = l];
  66.   <T>* top = &(s[len]);
  67.   <T>* t = s;
  68.   while (t < top) *t++ = fill_value;
  69. }
  70.  
  71.  
  72. <T>Vec& <T>Vec::operator = (const <T>Vec& v)
  73. {
  74.   if (this != &v)
  75.   {
  76.     delete [] s;
  77.     s = new <T> [len = v.len];
  78.     <T>* top = &(s[len]);
  79.     <T>* t = s;
  80.     const <T>* u = v.s;
  81.     while (t < top) *t++ = *u++;
  82.   }
  83.   return *this;
  84. }
  85.  
  86. void <T>Vec::apply(<T>Procedure f)
  87. {
  88.   <T>* top = &(s[len]);
  89.   <T>* t = s;
  90.   while (t < top) (*f)(*t++);
  91. }
  92.  
  93. // can't just realloc since there may be need for constructors/destructors
  94. void <T>Vec::resize(int newl)
  95. {
  96.   <T>* news = new <T> [newl];
  97.   <T>* p = news;
  98.   int minl = (len < newl)? len : newl;
  99.   <T>* top = &(s[minl]);
  100.   <T>* t = s;
  101.   while (t < top) *p++ = *t++;
  102.   delete [] s;
  103.   s = news;
  104.   len = newl;
  105. }
  106.  
  107. <T>Vec concat(<T>Vec & a, <T>Vec & b)
  108. {
  109.   int newl = a.len + b.len;
  110.   <T>* news = new <T> [newl];
  111.   <T>* p = news;
  112.   <T>* top = &(a.s[a.len]);
  113.   <T>* t = a.s;
  114.   while (t < top) *p++ = *t++;
  115.   top = &(b.s[b.len]);
  116.   t = b.s;
  117.   while (t < top) *p++ = *t++;
  118.   return <T>Vec(newl, news);
  119. }
  120.  
  121.  
  122. <T>Vec combine(<T>Combiner f, <T>Vec& a, <T>Vec& b)
  123. {
  124.   int newl = (a.len < b.len)? a.len : b.len;
  125.   <T>* news = new <T> [newl];
  126.   <T>* p = news;
  127.   <T>* top = &(a.s[newl]);
  128.   <T>* t = a.s;
  129.   <T>* u = b.s;
  130.   while (t < top) *p++ = (*f)(*t++, *u++);
  131.   return <T>Vec(newl, news);
  132. }
  133.  
  134. <T> <T>Vec::reduce(<T>Combiner f, <T&> base)
  135. {
  136.   <T> r = base;
  137.   <T>* top = &(s[len]);
  138.   <T>* t = s;
  139.   while (t < top) r = (*f)(r, *t++);
  140.   return r;
  141. }
  142.  
  143. <T>Vec reverse(<T>Vec& a)
  144. {
  145.   <T>* news = new <T> [a.len];
  146.   if (a.len != 0)
  147.   {
  148.     <T>* lo = news;
  149.     <T>* hi = &(news[a.len - 1]);
  150.     while (lo < hi)
  151.     {
  152.       <T> tmp = *lo;
  153.       *lo++ = *hi;
  154.       *hi-- = tmp;
  155.     }
  156.   }
  157.   return <T>Vec(a.len, news);
  158. }
  159.  
  160. void <T>Vec::reverse()
  161. {
  162.   if (len != 0)
  163.   {
  164.     <T>* lo = s;
  165.     <T>* hi = &(s[len - 1]);
  166.     while (lo < hi)
  167.     {
  168.       <T> tmp = *lo;
  169.       *lo++ = *hi;
  170.       *hi-- = tmp;
  171.     }
  172.   }
  173. }
  174.  
  175. int <T>Vec::index(<T&> targ)
  176. {
  177.   for (int i = 0; i < len; ++i) if (<T>EQ(targ, s[i])) return i;
  178.   return -1;
  179. }
  180.  
  181. <T>Vec map(<T>Mapper f, <T>Vec& a)
  182. {
  183.   <T>* news = new <T> [a.len];
  184.   <T>* p = news;
  185.   <T>* top = &(a.s[a.len]);
  186.   <T>* t = a.s;
  187.   while(t < top) *p++ = (*f)(*t++);
  188.   return <T>Vec(a.len, news);
  189. }
  190.  
  191. int operator == (<T>Vec& a, <T>Vec& b)
  192. {
  193.   if (a.len != b.len)
  194.     return 0;
  195.   <T>* top = &(a.s[a.len]);
  196.   <T>* t = a.s;
  197.   <T>* u = b.s;
  198.   while (t < top) if (!(<T>EQ(*t++, *u++))) return 0;
  199.   return 1;
  200. }
  201.  
  202. void <T>Vec::fill(<T&> val, int from, int n)
  203. {
  204.   int to;
  205.   if (n < 0)
  206.     to = len - 1;
  207.   else
  208.     to = from + n - 1;
  209.   if ((unsigned)from > (unsigned)to)
  210.     range_error();
  211.   <T>* t = &(s[from]);
  212.   <T>* top = &(s[to]);
  213.   while (t <= top) *t++ = val;
  214. }
  215.  
  216. <T>Vec <T>Vec::at(int from, int n)
  217. {
  218.   int to;
  219.   if (n < 0)
  220.   {
  221.     n = len - from;
  222.     to = len - 1;
  223.   }
  224.   else
  225.     to = from + n - 1;
  226.   if ((unsigned)from > (unsigned)to)
  227.     range_error();
  228.   <T>* news = new <T> [n];
  229.   <T>* p = news;
  230.   <T>* t = &(s[from]);
  231.   <T>* top = &(s[to]);
  232.   while (t <= top) *p++ = *t++;
  233.   return <T>Vec(n, news);
  234. }
  235.  
  236. <T>Vec merge(<T>Vec & a, <T>Vec & b, <T>Comparator f)
  237. {
  238.   int newl = a.len + b.len;
  239.   <T>* news = new <T> [newl];
  240.   <T>* p = news;
  241.   <T>* topa = &(a.s[a.len]);
  242.   <T>* as = a.s;
  243.   <T>* topb = &(b.s[b.len]);
  244.   <T>* bs = b.s;
  245.  
  246.   for (;;)
  247.   {
  248.     if (as >= topa)
  249.     {
  250.       while (bs < topb) *p++ = *bs++;
  251.       break;
  252.     }
  253.     else if (bs >= topb)
  254.     {
  255.       while (as < topa) *p++ = *as++;
  256.       break;
  257.     }
  258.     else if ((*f)(*as, *bs) <= 0)
  259.       *p++ = *as++;
  260.     else
  261.       *p++ = *bs++;
  262.   }
  263.   return <T>Vec(newl, news);
  264. }
  265.  
  266. static int gsort(<T>*, int, <T>Comparator);
  267.  
  268. void <T>Vec::sort (<T>Comparator compar)
  269. {
  270.   gsort(s, len, compar);
  271. }
  272.  
  273.  
  274. // An adaptation of Schmidt's new quicksort
  275.  
  276. static inline void SWAP(<T>* A, <T>* B)
  277. {
  278.   <T> tmp = *A; *A = *B; *B = tmp;
  279. }
  280.  
  281. /* This should be replaced by a standard ANSI macro. */
  282. #define BYTES_PER_WORD 8
  283. #define BYTES_PER_LONG 4
  284.  
  285. /* The next 4 #defines implement a very fast in-line stack abstraction. */
  286.  
  287. #define STACK_SIZE (BYTES_PER_WORD * BYTES_PER_LONG)
  288. #define PUSH(LOW,HIGH) do {top->lo = LOW;top++->hi = HIGH;} while (0)
  289. #define POP(LOW,HIGH)  do {LOW = (--top)->lo;HIGH = top->hi;} while (0)
  290. #define STACK_NOT_EMPTY (stack < top)                
  291.  
  292. /* Discontinue quicksort algorithm when partition gets below this size.
  293.    This particular magic number was chosen to work best on a Sun 4/260. */
  294. #define MAX_THRESH 4
  295.  
  296.  
  297. /* Order size using quicksort.  This implementation incorporates
  298.    four optimizations discussed in Sedgewick:
  299.    
  300.    1. Non-recursive, using an explicit stack of pointer that
  301.       store the next array partition to sort.  To save time, this
  302.       maximum amount of space required to store an array of
  303.       MAX_INT is allocated on the stack.  Assuming a 32-bit integer,
  304.       this needs only 32 * sizeof (stack_node) == 136 bits.  Pretty
  305.       cheap, actually.
  306.  
  307.    2. Chose the pivot element using a median-of-three decision tree.
  308.       This reduces the probability of selecting a bad pivot value and 
  309.       eliminates certain extraneous comparisons.
  310.  
  311.    3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving
  312.       insertion sort to order the MAX_THRESH items within each partition.  
  313.       This is a big win, since insertion sort is faster for small, mostly
  314.       sorted array segements.
  315.    
  316.    4. The larger of the two sub-partitions is always pushed onto the
  317.       stack first, with the algorithm then concentrating on the
  318.       smaller partition.  This *guarantees* no more than log (n)
  319.       stack size is needed! */
  320.       
  321. static int gsort (<T> *base_ptr, int total_elems, <T>Comparator cmp)
  322. {
  323. /* Stack node declarations used to store unfulfilled partition obligations. */
  324.   struct stack_node {  <T> *lo;  <T> *hi; };
  325.   <T>   pivot_buffer;
  326.   int   max_thresh   = MAX_THRESH;
  327.  
  328.   if (total_elems > MAX_THRESH)
  329.     {
  330.       <T>       *lo = base_ptr;
  331.       <T>       *hi = lo + (total_elems - 1);
  332.       <T>       *left_ptr;
  333.       <T>       *right_ptr;
  334.       stack_node stack[STACK_SIZE]; /* Largest size needed for 32-bit int!!! */
  335.       stack_node *top = stack + 1;
  336.  
  337.       while (STACK_NOT_EMPTY)
  338.         {
  339.           {
  340.             <T> *pivot = &pivot_buffer;
  341.             {
  342.               /* Select median value from among LO, MID, and HI. Rearrange
  343.                  LO and HI so the three values are sorted. This lowers the 
  344.                  probability of picking a pathological pivot value and 
  345.                  skips a comparison for both the LEFT_PTR and RIGHT_PTR. */
  346.  
  347.               <T> *mid = lo + ((hi - lo) >> 1);
  348.  
  349.               if ((*cmp) (*mid, *lo) < 0)
  350.                 SWAP (mid, lo);
  351.               if ((*cmp) (*hi, *mid) < 0)
  352.               {
  353.                 SWAP (mid, hi);
  354.                 if ((*cmp) (*mid, *lo) < 0)
  355.                   SWAP (mid, lo);
  356.               }
  357.               *pivot = *mid;
  358.               pivot = &pivot_buffer;
  359.             }
  360.             left_ptr  = lo + 1;
  361.             right_ptr = hi - 1; 
  362.  
  363.             /* Here's the famous ``collapse the walls'' section of quicksort.  
  364.                Gotta like those tight inner loops!  They are the main reason 
  365.                that this algorithm runs much faster than others. */
  366.             do 
  367.               {
  368.                 while ((*cmp) (*left_ptr, *pivot) < 0)
  369.                   left_ptr += 1;
  370.  
  371.                 while ((*cmp) (*pivot, *right_ptr) < 0)
  372.                   right_ptr -= 1;
  373.  
  374.                 if (left_ptr < right_ptr) 
  375.                   {
  376.                     SWAP (left_ptr, right_ptr);
  377.                     left_ptr += 1;
  378.                     right_ptr -= 1;
  379.                   }
  380.                 else if (left_ptr == right_ptr) 
  381.                   {
  382.                     left_ptr += 1;
  383.                     right_ptr -= 1;
  384.                     break;
  385.                   }
  386.               } 
  387.             while (left_ptr <= right_ptr);
  388.  
  389.           }
  390.  
  391.           /* Set up pointers for next iteration.  First determine whether
  392.              left and right partitions are below the threshold size. If so, 
  393.              ignore one or both.  Otherwise, push the larger partition's
  394.              bounds on the stack and continue sorting the smaller one. */
  395.  
  396.           if ((right_ptr - lo) <= max_thresh)
  397.             {
  398.               if ((hi - left_ptr) <= max_thresh) /* Ignore both small partitions. */
  399.                 POP (lo, hi); 
  400.               else              /* Ignore small left partition. */  
  401.                 lo = left_ptr;
  402.             }
  403.           else if ((hi - left_ptr) <= max_thresh) /* Ignore small right partition. */
  404.             hi = right_ptr;
  405.           else if ((right_ptr - lo) > (hi - left_ptr)) /* Push larger left partition indices. */
  406.             {                   
  407.               PUSH (lo, right_ptr);
  408.               lo = left_ptr;
  409.             }
  410.           else                  /* Push larger right partition indices. */
  411.             {                   
  412.               PUSH (left_ptr, hi);
  413.               hi = right_ptr;
  414.             }
  415.         }
  416.     }
  417.  
  418.   /* Once the BASE_PTR array is partially sorted by quicksort the rest
  419.      is completely sorted using insertion sort, since this is efficient 
  420.      for partitions below MAX_THRESH size. BASE_PTR points to the beginning 
  421.      of the array to sort, and END_PTR points at the very last element in
  422.      the array (*not* one beyond it!). */
  423.  
  424.  
  425.   {
  426.     <T> *end_ptr = base_ptr + 1 * (total_elems - 1);
  427.     <T> *run_ptr;
  428.     <T> *tmp_ptr = base_ptr;
  429.     <T> *thresh  = (end_ptr < (base_ptr + max_thresh))? 
  430.       end_ptr : (base_ptr + max_thresh);
  431.  
  432.     /* Find smallest element in first threshold and place it at the
  433.        array's beginning.  This is the smallest array element,
  434.        and the operation speeds up insertion sort's inner loop. */
  435.  
  436.     for (run_ptr = tmp_ptr + 1; run_ptr <= thresh; run_ptr += 1)
  437.       if ((*cmp) (*run_ptr, *tmp_ptr) < 0)
  438.         tmp_ptr = run_ptr;
  439.  
  440.     if (tmp_ptr != base_ptr)
  441.       SWAP (tmp_ptr, base_ptr);
  442.  
  443.     /* Insertion sort, running from left-hand-side up to `right-hand-side.' 
  444.        Pretty much straight out of the original GNU qsort routine. */
  445.  
  446.     for (run_ptr = base_ptr + 1; (tmp_ptr = run_ptr += 1) <= end_ptr; )
  447.       {
  448.  
  449.         while ((*cmp) (*run_ptr, *(tmp_ptr -= 1)) < 0)
  450.           ;
  451.  
  452.         if ((tmp_ptr += 1) != run_ptr)
  453.           {
  454.             <T> *trav;
  455.  
  456.             for (trav = run_ptr + 1; --trav >= run_ptr;)
  457.               {
  458.                 <T> c = *trav;
  459.                 <T> *hi, *lo;
  460.  
  461.                 for (hi = lo = trav; (lo -= 1) >= tmp_ptr; hi = lo)
  462.                   *hi = *lo;
  463.                 *hi = c;
  464.               }
  465.           }
  466.  
  467.       }
  468.   }
  469.   return 1;
  470. }
  471.